/**
 * Created by ss on 15/12/23.
 */
import $ from "jquery";
import Helper from "./helper";
//时间格式化
Date.prototype.format =function(format)
{
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "h+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S+" : this.getMilliseconds()
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (this.getFullYear()+"").substr(4- RegExp.$1.length));
    if(new RegExp("(S+)").test(format)){
        format=format.replace(RegExp.$1,
            RegExp.$1.length==1? o["S+"] :
                ("000"+ o["S+"]).substr((""+ o["S+"]).length));
    }
    for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length==1? o[k] :
                ("00"+ o[k]).substr((""+ o[k]).length));

    return format;
}
let Render = {
    winWidth : $(window).width(),
    winHeight : $(window).height(),
    startDatePicker : null,
    dom : {},
    domList : {
        nameInput : ".input[name='name']",
        teleInput : ".input[name='tele']",
        startDateInput : "#startDatePicker",
        endDateInput : "#endDatePicker",
        priceTotalBefore : "#priceTotalBefore",
        priceCoupon : "#priceCoupon",
        priceTotalAfter : ".priceTotalAfter",
        lastDay : "#lastDay",
        leftWords : ".left_word",
        remarks : "textarea[name='extra']",
        title: "#header"
    },
    data : {
        orderId : 0,
        customerName : "",
        customerPhone : "",
        startDate : "",
        endDate : "",
        startTime : "",
        endTime : "",
        orderItems : new Array(),
        priceTotalBefore : 0 ,
        discount : 0 ,
        priceTotalAfter : 0,
        lastDay : 0 ,
        remark : "" ,
        orderStatus : "1"
    },
    optionHtml: "",

    getOptionHtml(){
        var html = "";
        for(var i = 0 ; i < 20 ; i++){
            html += "<option value='"+i+"'>"+i+"</option>";
        }
        this.optionHtml = html;
    },

    init(config){

        this.findDom();

        this.getOptionHtml();

        this.formatData(config.data);

        this.dom.nameInput.val(this.data.customerName);
        this.dom.teleInput.val(this.data.customerPhone);
        this.dom.remarks.val(this.data.remark);
        this.dom.leftWords.html(this.data.remark.length);

        this.initEvent();

        this.render();

    },

    findDom(){
        for(var i in this.domList){
            this.dom[i] = $(this.domList[i]);
        }
    },

    formatData(data){

        if(data){
            $.extend(this.data,data);
        }

        this.data.priceTotalBefore = 0;
        for(var i = 0 ; i < this.data.orderItems.length ; i++ ){
            var item = this.data.orderItems[i];
            this.data.priceTotalBefore += item.amount*item.price;
        }
        this.data.priceTotalAfter = this.data.priceTotalBefore - this.data.discount;
        var flag = true;
        if(this.data.startTime){
            this.data.startDate = this.data.startTime.format("yyyy-MM-dd");
        }else{
            this.data.startDate = "";
            flag = false;
        }
        if(this.data.endTime){
            this.data.endDate = this.data.endTime.format("yyyy-MM-dd");
        }else{
            this.data.endDate = "";
            flag = false
        }

        if(flag){
            this.data.lastDay = (this.data.endTime.getTime()-this.data.startTime.getTime())/1000/60/60/24;
        }
        if(this.data.priceTotalAfter < 0) {
            this.data.priceTotalAfter = 0;
        }

    },

    setData(data){

        $.extend(this.data,data);

        this.formatData();

        //this.render();

    },

    updatePrice(startDate,endDate,orderId){
        var deferred = $.Deferred();
        if(startDate && endDate) {
            deferred = Helper.ajax({
                url : "/order/getPriceAndInventory",
                data : {
                    startDate : startDate,
                    endDate : endDate,
                    orderId : orderId
                }
            })
        }else{
            deferred.resolve();
        }
        return deferred;
    },

    initEvent(){

        var self = this;
        var start = {
            elem: '#startDatePicker',
            min : laydate.now(),
            max : self.data.endDate,
            choose : function(dates){
                end.min = dates; //开始日选好后，重置结束日的最小日期
                end.start = dates //将结束日的初始值设定为开始日
                var object = new Object();
                $.extend(object,self.data);
                object.startTime = Helper.hackDate(dates);
                self.updatePrice(dates, self.data.endDate, self.data.orderId).then(function(inventor){
                    var newResult = self.mergePrice(self.data.orderItems,inventor.data.list);
                    self.setData({
                        startTime : object.startTime,
                        orderItems : newResult
                    })
                    self.render();
                })

            }
        }

        var end = {
            elem: '#endDatePicker',
            min : self.data.startDate,
            max: '2099-06-16 23:59:59',
            choose : function(dates){
                start.max = dates; //结束日选好后，重置开始日的最大日期
                var object = new Object();
                $.extend(object,self.data);
                object.endTime = Helper.hackDate(dates);
                self.updatePrice(self.data.startDate, dates, self.data.orderId).then(function(inventor){
                    var newResult = self.mergePrice(self.data.orderItems,inventor.data.list);
                    self.setData({
                        endTime : object.endTime,
                        orderItems : newResult
                    })
                    self.render();
                })
            }
        }

        //初始化时间控件

        ;!function(){

            laydate(start);

            laydate(end);

        }();

        //初始化点击事件

        $("body").on("touchend",".num-del",function(){

            var index = $(this).parents(".goods-item").attr("index");

            if(self.data.orderItems[index].amount){

                self.data.orderItems[index].amount--;

                self.setData({
                    orderItems : self.data.orderItems
                })

                self.smallRender(index);

            }

        })

        $("body").on("touchend",".num-add",function(){

            var index = $(this).parents(".goods-item").attr("index");

            var object = {};

            $.extend(object,self.data.orderItems);

            object[index].amount++;

            self.setData({
                orderItems : object
            })

            self.smallRender(index);

        })

        $("body").on("change",".hidden_select",function(){

            var index = $(this).parents(".goods-item").attr("index");

            var object = {};

            $.extend(object,self.data.orderItems);

            object[index].amount = $(this).val();

            self.setData({
                orderItems : object
            })

            self.smallRender(index);

        })

        $("textarea[name='extra']").keyup(function(){
            var maxLength = 120;
            var value = $(this).val();
            var length = value.length;
            if(length>maxLength){
                $(this).val(value.substr(0,maxLength));
                self.dom.leftWords.addClass("full");
                length=maxLength;
            }else{
                self.dom.leftWords.removeClass("full");
            }
            self.dom.leftWords.html(length);
        })

        $("#submit_button").click(function(){
            //收集一下数据
            var post = $.extend({},self.data);
            post.customerName = self.dom.nameInput.val();
            post.customerPhone = self.dom.teleInput.val();
            post.remark = self.dom.remarks.val();
            //将orderItems整理成数组
            post.orderItems = Array.prototype.slice.call(post.orderItems);
            post.orderItems = JSON.stringify(post.orderItems);
            Helper.ajax({
                type : "get",
                url : "/order/modifyTeamOrder",
                data : post
            }).then(function (data) {
                if(data.code == "1"){
                    alert("预订成功");
                    //window.location.reload();
                }else{
                    alert("似乎出现了一些错误");
                    //window.location.reload();
                }
            })
        })
        


    },

    smallRender(index){
        var parent = $(".goods-item[index='"+index+"']");
        var item = this.data.orderItems[index];
        parent
            .find('.item_num').find(".num-num").html(item.amount);
        parent.find('.footer').html('<div class="price">￥ '+item.price+'<span>x'+item.amount+'</span></div>'+
            '<div class="price-total">￥ '+item.amount*item.price+'</div>');
        this.dom.priceTotalBefore.html(this.data.priceTotalBefore);
        this.dom.priceCoupon.html(this.data.discount);
        this.dom.priceTotalAfter.html(this.data.priceTotalAfter);
    },

    render(){
        var html = "";
        for(var i = 0 ; i < this.data.orderItems.length ; i++){
            var item = this.data.orderItems[i];
            html += ""+
                '<li class="goods-item" index="'+i+'">'+
                    '<div class="title">'+
                        '<span class="item-name">'+
                            item.name+
                        '</span>'+
                        '<div class="item_num">'+
                            '<span class="num-del button"></span>'+
                            '<div class="num-container">' +
                                '<span class="num-num">'+item.amount+'</span>'+
                                '<select class="hidden_select">'+this.optionHtml+'</select>'+
                            '</div>'+
                            '<span class="num-add button"></span>'+
                        '</div>'+
                    '</div>'+
                    '<div class="footer">'+
                        '<div class="price">￥ '+item.price+'<span>x'+item.amount+'</span></div>'+
                        '<div class="price-total">￥ '+item.amount*item.price+'</div>'+
                    '</div>'+
                '</li>';
        }
        $(".goods-container").html(html);
        this.dom.title.html(this.data.origin);
        if(this.data.orderStatus == 2){
            $("footer.footer").remove();
            $(".button").hide();
        }else if(this.data.orderStatus == 3){
            $("body").html("<img src='http://doc.eluying.com/1451744091172TP4G.jpg' width='100%' style='display: block'/>");
        }else if(this.data.orderStatus == 1){
            this.dom.startDateInput.val(this.data.startDate);
            this.dom.endDateInput.val(this.data.endDate);
            this.dom.priceTotalBefore.html(this.data.priceTotalBefore);
            this.dom.priceCoupon.html(this.data.discount);
            this.dom.priceTotalAfter.html(this.data.priceTotalAfter);
            this.dom.lastDay.html(this.data.lastDay);
        }


    },

    mergePrice(oldData,newData){
        var oldDataCopy = $.extend({},oldData);
        oldDataCopy.length = oldData.length;
        for(var i = 0 , l = newData.length ; i < l ; i++ ){
            for(var j = 0 , l1 = oldData.length ; j < l1 ; j++){
                var newItem = newData[i];
                if(oldData[j].typeId == newItem.typeId){
                    oldDataCopy[j].price = newItem.price;
                    oldDataCopy[j].inventory = newItem.inventory;
                    break;
                }
            }
        }
        return oldDataCopy;
    }
}
export default Render;